package com.assisjrs.jpaandroid.persistence.converter;

import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.database.Cursor;

import com.assisjrs.jpaandroid.persistence.ConverterDatabase;
import com.assisjrs.jpaandroid.persistence.Entity;

public class TimestampConverter implements ConverterDatabase<Date, String> {
	private static final String TIMESTAMP_FORMAT = "yyyy-MM-dd HH:mm:ss";
	private final SimpleDateFormat dateFormat = new SimpleDateFormat(TIMESTAMP_FORMAT);

	@SuppressWarnings("deprecation")
	public Date getToInstance(final Cursor cursor, final int columnIndex, final Class<?> type) {
		final String value = cursor.getString(columnIndex);

		if (value == null || "".equals(value.trim()))
			return null;

		try {
			final Date timestamp = dateFormat.parse(value);

			return new java.sql.Timestamp(timestamp.getYear(), timestamp.getMonth(), timestamp.getDate(), timestamp
			        .getHours(), timestamp.getMinutes(), timestamp.getSeconds(), 0);
		} catch (final ParseException e) {
			throw new RuntimeException(e);
		}
	}

	public String getFromInstance(final Field field, final Entity entity) {
		try {
			final Date value = (Date) field.get(entity);

			if (value == null)
				return "";

			return dateFormat.format(value);
		} catch (final IllegalArgumentException e) {
			throw new RuntimeException(e);
		} catch (final IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	}
}
